import api from "../../../common/api";
import util from "../../../utils/util.js";
import * as transferData from "../../../models/transferData";
const computedBehavior = require("miniprogram-computed");
var app = getApp();
Page({
  behaviors: [computedBehavior],
  data: {
    height: 0,
    top: 0,
    isShowImg: '',
    showReview: false, //是否是审核中
    noReview: false, //审核未通过
    noReviewTmp:false, //出现重新上传按钮
    noPassReason: '', //
    imgArray: [], //图片数组
    imgMin: 1, //最小图片数
    imgMax: 2, //最大图片数
    iconList: [{
        id: 1,
        url: '../images/cardHolder.png',
        name: '上传名片',
      },
      {
        id: 2,
        url: '../images/confirm.png',
        name: '确认信息',
      },
      {
        id: 3,
        url: '../images/audit.png',
        name: '平台审核',
      },
      {
        id: 4,
        url: '../images/insurance.png',
        name: '发布合作',
      },
    ],
    fileId: [],
    authSource: '',//短信链接的参数
  },
  computed: {
    // isShowImg(data){
    //   return data.imgArray.length
    // }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true,
    });
    getApp().globalData.loginPromise.then(() => {
      this.getNavHeight(); //自定义导航栏高度
      this.getInfoList(options.type == 'share')
      if (options.type == 'share') {
        transferData.setData('fromUserId', options.userId)
        api.recordInvitedAuthentication({fromUserId:options.userId},(res)=>{})
      }
      if(options.authSource){
        this.setData({
          authSource:3
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function (e) {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = getApp().globalData.sessionUser.id
    let result = {
      title: '可信赖的房地产经纪人合作平台',
      path: `/pages/cooperation/editCertification/editCertification?type=share&userId=${userId}&agentId=${userId}`,
      imageUrl: 'https://shulan-prod.oss-cn-shanghai.aliyuncs.com/static/jjrjs/resource/recommend_join.png',
    }
    return result
  },

  //查询数据
  getInfoList(tmp) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '加载中...',
      })
      api.getAuthenticationInfo({}, (res) => {
        if (res && res.data && res.data.content) {
          let authStatus = res.data.content.authStatus //(1: 待审核 2:审核通过 3:取消审核 4:审核不通过)
          let imgList = res.data.content.imgList || []
          let verified = res.data.content.verified
          if(tmp){
            getApp().mobileLogin(false, '认证信息', false).then(() => {
                if (verified) {
                  wx.redirectTo({
                    url: '/pages/cooperation/authentication/authentication',
                  })
                } else {
                  wx.redirectTo({
                    url: '/pages/cooperation/editCertification/editCertification',
                  })
                }
                })
              .catch(() => {
                app.globalData.afterMobileAuthorCallBack = () => {
                  wx.redirectTo({
                    url: '/pages/cooperation/editCertification/editCertification',
                  })
                };
              })
          } else {
          imgList = imgList.map((item) => {
            return {url: item}
          })
          if (authStatus) {
            if(authStatus==1){
              this.setData({
                showReview: true,
                imgArray: imgList
              })
            }
            if(authStatus==4){
              this.setData({
                noReview: true,
                noReviewTmp:true,
                imgArray: imgList,
                noPassReason: res.data.content.noPassReason
              })
            }
            if(authStatus==3){
              this.setData({
                showReview: false
              })
            }
          } else {
            this.setData({
              showReview: false
            })
          }
        }
          wx.hideLoading()
          resolve()
        }
      })
    })

  },

  // 加入合作
  joinCoopertion() {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '加载中...',
      })
      let {
        imgArray,
        authSource
      } = this.data
      let refresh = transferData.getData("fromUserId");
        transferData.resetData("fromUserId");
      let fileId = []
      for (let i in imgArray) {
        fileId.push(imgArray[i].fileId)
      }
      api.applyForAuthentication({
        fileId,
        fromUserId:refresh,
        authSource
      }, (res) => {
        if (res && res.data && res.data.isSuccess) {
          if(res.data.content==2){
            wx.redirectTo({
              url: '/pages/cooperation/authentication/authentication',
            })
          } else {
            wx.showToast({
              title: res.data.successMessage,
              icon: 'none',
              duration: 1000
            })
            wx.hideLoading()
            this.setData({
              showReview: true,
            })
          }
        }
      })
    })

  },

  // 设置导航栏的高度
  getNavHeight() {
    this.setData({
      height: app.globalData.navHeight,
      top: app.globalData.navTop,
    })
  },
  // 点击返回按钮
  goToBack() {
    wx.redirectTo({
      url: '/pages/index/index?tabConentIndex=3',
    })
  },
  //联系客服
  gotoHelp() {
    api.getPrivateSale({}, (res1) => {
      wx.makePhoneCall({
        phoneNumber: res1.data.content.serviceMobile,
        success() {},
        fail() {},
      });
    });
  },
  //上传图片
  updownd(e) {
    let num = this.data.imgMax - this.data.imgArray.length;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      count: num,
      success: (res) => {
        let filePathArr = res.tempFilePaths;
        let promiseList = filePathArr.map((item) => {
          return new Promise((resolve, reject) => {
            util.uploadFiles(item, (res) => {
              try {
                var id = JSON.parse(res.data)[0].id;
                var obj = {
                  fileId: id,
                  url: item,
                };
                resolve(obj);
              } catch (error) {
                reject()
              }
            });
          });
        });
        Promise.all(promiseList).then((list) => {
          if(e.currentTarget.dataset.type=='again'){ //重新上传先清空数据
            this.setData({
              imgArray: [],
              noReviewTmp:false
            });
          }
          this.setData({
            imgArray: this.data.imgArray.concat(list)
          });
        });
      },
    });
  },
  // 图片删除
  handleCancel(e) {
    let id = e.currentTarget.dataset.fileid;
    this.setData({
      imgArray: this.data.imgArray.filter((v) => v.fileId != id),
    });
  },
})